import React, { useState, useEffect } from 'react';
import { message, Tabs, List, Select, Button, Modal } from 'antd';
import { connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import FileOpen from '@/components/FileIframOpen';
import EditorContent from './editorContent';
import BoardDetail from './boardDetail';
import Materials from './materials';
import moment from 'moment';
import { getPublicity } from '@/services/login';
import { deletePublicity } from '@/services/public';
import './index.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';

let pageNo = 1;

interface BulletinBoardProps {
  style?: any;
  typeEnum?: string;
  currentUser?: CurrentUser;
}

const BulletinBoard: React.FC<BulletinBoardProps> = ({
  style,
  typeEnum,
  currentUser: { perms = [''] },
}) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [total, setTotal] = useState<number>(0);
  const [activeKey, setActiveKey] = useState<string>('5');
  const [selectValue, setSelectValue] = useState<string>('0');
  const [list, setList] = useState<any[]>([]);
  const [fileUrl, setFileUrl] = useState<string>('');
  const [fileName, setFileName] = useState<string>('');
  const [showFile, setShowFile] = useState<boolean>(false);
  const [showNoti, setShowNoti] = useState<boolean>(false);
  const [showMaterial, setShowMaterial] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [infor, setInfo] = useState<any>({});

  const judgePerms = () => {
    if (perms.indexOf(typeEnum) > -1) {
      return true;
    } else {
      return false;
    }
  };

  const down = (url: string, title: string) => {
    message.loading('正在下载, 若无法下载请检查浏览器是否拦截', 4);
    const files = url.split(',');
    const open = (index) => {
      const element = files[index];
      const nowTime = moment().format('YYYYMMDDHHmm');
      const name = title ? title : nowTime;
      const fileurl = element.split('?');

      window.open(`/open/publicity/downloadFile?fileName=${name.replace(/#/g, "23%")}&fileUrl=${(fileurl[0]).replace(/#/g, "23%")}`);
    };

    for (let index = 0; index < files.length; index++) {
      if (index !== 0) {
        setTimeout(() => {
          open(index);
        }, 1000);
      } else {
        open(index);
      }
    }
  };

  const requsetList = async (type: string) => {
    setLoading(true);
    const par: any = {
      pageSize: 20,
      pageNo: pageNo,
    };
    par.type = type;
    const res = await getPublicity(par);
    setLoading(false);
    if (res && res.success) {
      setList(res.data || []);
      setTotal(res.total);
    } else {
      message.error(res.errMsg || '请求错误');
    }
  };

  useEffect(() => {
    requsetList(activeKey);
  }, []);

  const paginationProps = {
    showSizeChanger: false,
    showQuickJumper: false,
    pageSize: 20,
    size: 'small',
    total: total,
    current: pageNo,
    onChange: (page, pageSize) => {
      pageNo = page;
      requsetList(selectValue != '0' ? selectValue : activeKey);
    },
  };

  const typeTitle = (type: number) => {
    if (type == 1) return '差异化公示';
    if (type == 2) return '工资发放表公示';
    if (type == 3) return '销户公告公示';
    return '';
  };

  const onChange = (select: string) => {
    pageNo = 1;
    setActiveKey(select);
    if (select == '0') {
      requsetList(selectValue);
    } else {
      requsetList(select);
    }
  };

  const handleChange = (value: string) => {
    pageNo = 1;
    setSelectValue(value);
    requsetList(value);
  };

  return (
    <div style={style || {}}>
      <div className="boardDiv">
        <Tabs
          style={{ padding: '0 20px' }}
          defaultActiveKey="5"
          activeKey={activeKey}
          onChange={onChange}
        >
          <Tabs.TabPane tab="政务公开" key="5" />
          <Tabs.TabPane tab="公示公告" key="0" />
          {/* <Tabs.TabPane tab="差异化公示" key="1" />
          <Tabs.TabPane tab="工资发放表公示" key="2" />
          <Tabs.TabPane tab="销户公告公示" key="3" /> */}
          <Tabs.TabPane tab="通知告示" key="4" />

        </Tabs>
        {activeKey == '0' && (
          <div className="publicity">
            <Select
              defaultValue="0"
              value={selectValue}
              style={{ width: '200px', margin: '2px 5px 25px 8px' }}
              onChange={handleChange}
              options={[
                {
                  value: '0',
                  label: '全部',
                },
                {
                  value: '1',
                  label: '差异化公示',
                },
                {
                  value: '2',
                  label: '工资发放表公示',
                },
                {
                  value: '3',
                  label: '销户公告公示',
                },
              ]}
            />
            <List
              size="small"
              rowKey="id"
              loading={loading}
              pagination={pageNo == 1 && list.length <= 0 ? false : paginationProps}
              dataSource={list}
              renderItem={(item) => (
                <List.Item
                  style={{ cursor: 'pointer' }}
                  onClick={() => {
                    if (item.fileUrl) {
                      setFileUrl(item.fileUrl);
                      setShowFile(true);
                    }
                  }}
                >
                  <List.Item.Meta
                    title={
                      <a>
                        [{typeTitle(item.type)}]
                        {item.departmentName ? '(' + item.departmentName + ')' : ''}
                        {item.title}
                      </a>
                    }
                    className="metaTitle"
                  />
                  <div>{moment(item.gmtCreate).format('YYYY-MM-DD')}</div>
                </List.Item>
              )}
            />
          </div>
        )}
        {activeKey == '4' && (
          <div className="publicity">
            {judgePerms() && (
              <div style={{ textAlign: 'center' }}>
                <Button
                  type={'primary'}
                  onClick={() => {
                    setInfo({});
                    setShowNoti(true);
                  }}
                >
                  下发通知
                </Button>
              </div>
            )}
            <List
              size="small"
              rowKey="id"
              loading={loading}
              pagination={pageNo == 1 && list.length <= 0 ? false : paginationProps}
              dataSource={list}
              renderItem={(item) => (
                <List.Item
                  style={{ cursor: 'pointer' }}
                  actions={
                    judgePerms()
                      ? [
                        <a
                          key="edit"
                          onClick={() => {
                            setInfo(item);
                            setShowNoti(true);
                          }}
                        >
                          编辑
                        </a>,
                        <a
                          key="dele"
                          onClick={() => {
                            Modal.confirm({
                              title: '确认删除当前通知吗？',
                              icon: <ExclamationCircleOutlined />,
                              content: '',
                              okText: '删除',
                              cancelText: '取消',
                              onOk: () => {
                                deletePublicity({ id: item.id })
                                  .then((res) => {
                                    if (res && res.success) {
                                      message.success('已删除');
                                      requsetList(activeKey);
                                    } else {
                                      message.error('删除失败');
                                    }
                                  })
                                  .catch(() => { });
                              },
                            });
                          }}
                        >
                          删除
                        </a>,
                      ]
                      : []
                  }
                >
                  <List.Item.Meta
                    title={<a>{item.title}</a>}
                    className="metaTitle"
                    onClick={() => {
                      setInfo(item);
                      setShowDetail(true);
                    }}
                  />
                  <div
                    onClick={() => {
                      setInfo(item);
                      setShowDetail(true);
                    }}
                  >
                    {moment(item.gmtCreate).format('YYYY-MM-DD')}
                  </div>
                </List.Item>
              )}
            />
          </div>
        )}
        {activeKey == '5' && (
          <div className="publicity">
            {judgePerms() && (
              <div style={{ textAlign: 'center' }}>
                <Button type={'primary'} onClick={() => setShowMaterial(true)}>
                  上传资料
                </Button>
              </div>
            )}
            <List
              size="small"
              rowKey="id"
              loading={loading}
              pagination={pageNo == 1 && list.length <= 0 ? false : paginationProps}
              dataSource={list}
              renderItem={(item) => (
                <List.Item
                  style={{ cursor: 'pointer' }}
                  actions={
                    judgePerms()
                      ? [
                        <a
                          key="edit"
                          onClick={() => {
                            down(item.attachmentUrl, item.title);
                          }}
                        >
                          下载
                        </a>,
                        <a
                          key="dele"
                          onClick={() => {
                            Modal.confirm({
                              title: '确认删除当前资料吗？',
                              icon: <ExclamationCircleOutlined />,
                              content: '',
                              okText: '删除',
                              cancelText: '取消',
                              onOk: () => {
                                deletePublicity({ id: item.id })
                                  .then((res) => {
                                    if (res && res.success) {
                                      message.success('已删除');
                                      requsetList(activeKey);
                                    } else {
                                      message.error('删除失败');
                                    }
                                  })
                                  .catch(() => { });
                              },
                            });
                          }}
                        >
                          删除
                        </a>,
                      ]
                      : [
                        <a
                          key="edit"
                          onClick={() => {
                            down(item.attachmentUrl, item.title);
                          }}
                        >
                          下载
                        </a>,
                      ]
                  }
                >
                  <List.Item.Meta
                    title={<a>{item.title}</a>}
                    className="metaTitle"
                    onClick={() => {
                      setFileName(item.title);
                      setFileUrl(item.attachmentUrl);
                      setShowFile(true);
                    }}
                  />
                  <div
                    onClick={() => {
                      setFileName(item.title);
                      setFileUrl(item.attachmentUrl);
                      setShowFile(true);
                    }}
                  >
                    {moment(item.gmtCreate).format('YYYY-MM-DD')}
                  </div>
                </List.Item>
              )}
            />
          </div>
        )}
      </div>
      {showFile && (
        <FileOpen
          title={fileName}
          fielUrl={fileUrl}
          modalVisible={showFile}
          onCancel={() => {
            setShowFile(false);
            setFileUrl('');
            setFileName('');
          }}
        />
      )}
      {showNoti && (
        <EditorContent
          visible={showNoti}
          info={infor}
          onCancel={() => {
            setShowNoti(false);
            setInfo({});
          }}
          onSubmit={() => {
            setShowNoti(false);
            setInfo({});
            requsetList(activeKey);
          }}
        />
      )}
      {showMaterial && (
        <Materials
          visible={showMaterial}
          onCancel={() => setShowMaterial(false)}
          onSubmit={() => {
            setShowMaterial(false);
            requsetList(activeKey);
          }}
        />
      )}
      {showDetail && (
        <BoardDetail visible={showDetail} info={infor} onCancel={() => setShowDetail(false)} />
      )}
    </div>
  );
};

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(BulletinBoard);
